<template>
  <div class="app-container">
    <!-- 搜索表单 - 保持原样 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文章标题" prop="articleTitle">
        <el-input v-model="queryParams.articleTitle" placeholder="请输入文章标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="文章状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择文章状态" clearable>
          <el-option v-for="dict in bk_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
          <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 - 保持原有功能 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="openNewPage()"
                   v-hasPermi="['bk:article:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['bk:article:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['bk:article:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['bk:article:export']">导出</el-button>
      </el-col>

      <!-- 视图切换 -->
      <el-col :span="6">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="card">卡片视图</el-radio-button>
          <el-radio-button label="table">表格视图</el-radio-button>
          <el-radio-button label="grid">网格视图</el-radio-button>
        </el-radio-group>
      </el-col>

      <el-col :span="4">
        <el-select v-model="sortOption" placeholder="排序方式" size="small">
          <el-option label="最新创建" value="createTimeDesc" />
          <el-option label="最早创建" value="createTimeAsc" />
          <el-option label="最近更新" value="updateTimeDesc" />
          <el-option label="标题排序" value="titleAsc" />
        </el-select>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 快速过滤标签 -->
    <el-row class="filter-tags mb8" v-show="hasFilter">
      <el-tag v-for="(item, index) in activeTags" :key="index" closable @close="removeFilter(item.type, item.value)">
        {{ item.label }}: {{ item.text }}
      </el-tag>
      <el-button link type="primary" v-show="activeTags.length > 0" @click="clearAllFilters">清除全部</el-button>
    </el-row>

    <!-- 卡片视图 -->
    <div v-if="viewMode === 'card'" v-loading="loading">
      <el-row :gutter="16">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="article in articleList" :key="article.id" class="mb16">
          <el-card :body-style="{ padding: '0px' }" shadow="hover">
            <div class="article-card-header">
              <!-- 使用原有的图片预览组件 -->
              <div class="card-image-container">
                <image-preview :src="article.articleImg" :width="'100%'" :height="180" />
              </div>
              <div class="card-status-tag">
                <dict-tag :options="bk_status" :value="article.status" />
              </div>
            </div>
            <div class="article-card-content">
              <div class="article-title">{{ article.articleTitle }}</div>
              <div class="article-excerpt">{{ article.articleExcerpt || '暂无简介' }}</div>
              <div class="article-meta">
                <span class="meta-item">
                  <i class="el-icon-folder"></i> {{ article.categoryName || '未分类' }}
                </span>
                <span class="meta-item">
                  <i class="el-icon-date"></i> {{ parseTime(article.updateTime, '{y}-{m}-{d}') }}
                </span>
              </div>
            </div>
            <div class="article-card-footer">
              <el-button type="text" @click="openNewPage(article.id)" v-hasPermi="['bk:article:edit']">编辑</el-button>
              <el-button type="text" @click="handleDelete(article)" v-hasPermi="['bk:article:remove']">删除</el-button>
              <el-button type="text" @click="WenZhangXiangQing(article)">查看</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 网格视图 -->
    <div v-else-if="viewMode === 'grid'" v-loading="loading">
      <el-row :gutter="12">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="article in articleList" :key="article.id" class="mb12">
          <div class="grid-item">
            <div class="grid-item-image">
              <!-- 使用原有的图片预览组件 -->
              <image-preview :src="article.articleImg" :width="'100%'" :height="120" />
              <div class="grid-status">
                <dict-tag :options="bk_status" :value="article.status" />
              </div>
            </div>
            <div class="grid-content">
              <h3 class="grid-title text-overflow">{{ article.articleTitle }}</h3>
              <p class="grid-category">{{ article.categoryName || '未分类' }}</p>
              <p class="grid-date">{{ parseTime(article.updateTime, '{y}-{m}-{d}') }}</p>
            </div>
            <div class="grid-actions">
              <el-button-group>
                <el-button size="small" @click="openNewPage(article.id)" v-hasPermi="['bk:article:edit']">编辑</el-button>
                <el-button size="small" @click="WenZhangXiangQing(article)">查看</el-button>
                <el-button size="small" type="danger" @click="handleDelete(article)"
                           v-hasPermi="['bk:article:remove']">删除</el-button>
              </el-button-group>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格视图 - 基于原有表格 -->
    <el-table v-else v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" width="80" />
      <el-table-column label="文章标题" align="left" prop="articleTitle" min-width="200">
        <template #default="scope">
          <div class="title-cell">
            <div class="article-title-preview">{{ scope.row.articleTitle }}</div>
            <div class="article-excerpt-preview">{{ scope.row.articleExcerpt }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="文章内容" align="center" prop="articleContent" width="100">
        <template #default="scope">
          <el-button type="success" @click="WenZhangXiangQing(scope.row)">查看内容</el-button>
        </template>
      </el-table-column>
      <el-table-column label="文章封面图" align="center" prop="articleImg" width="100">
        <template #default="scope">
          <!-- 保持原有的图片预览组件 -->
          <image-preview :src="scope.row.articleImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="文章分类" align="center" prop="categoryName" width="100" />
      <el-table-column label="文章状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="bk_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="openNewPage(scope.row.id)"
                     v-hasPermi="['bk:article:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['bk:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 保持原有的文章详情对话框 -->
    <el-dialog v-model="WenZhang" width="1200px" title="文章详情">
      <div v-html="form.articleContent">
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Article">
import { listHome } from "@/api/bk/home";
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/bk/article";
import { useRouter } from 'vue-router';
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/bk/category";

const { proxy } = getCurrentInstance();
const { bk_status } = proxy.useDict('bk_status');

const articleList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const WenZhang = ref(false);
const router = useRouter();
const viewMode = ref('card'); // 默认为表格视图
const sortOption = ref('updateTimeDesc'); // 默认排序方式
const hasFilter = ref(false);
const activeTags = ref([]);

// 定义分类选项（实际使用时需要通过API获取）
const categoryOptions = ref([
  { value: 1, label: '技术博客' },
  { value: 2, label: '生活随笔' },
  { value: 3, label: '项目记录' },
  { value: 4, label: '学习笔记' }
]);

const queryParamscategory =ref({

})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    articleTitle: null,
    articleContent: null,
    articleImg: null,
    articleExcerpt: null,
    categoryId: null,
    status: null
  },
  rules: {
    articleTitle: [
      { required: true, message: "文章标题不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

function getListcategory() {
  listCategory(queryParams.value).then(response => {
    categoryOptions.value = response.rows;
  });
}

// 保留原有的文章查看详情功能
function WenZhangXiangQing(row) {
  const _id = row.id || ids.value
  getArticle(_id).then(response => {
    form.value = response.data;
    WenZhang.value = true;
  });
}

// 保留原有的新页面打开编辑器功能
const openNewPage = (id) => {
  const url = id ? `/articleManage/change?id=${id}` : '/articleManage/change';
  window.open(url, '_blank');
}

// 根据排序选项调整获取数据
function getList() {
  loading.value = true;

  // 添加排序参数
  const params = { ...queryParams.value };

  // 根据选择的排序选项设置排序参数
  switch (sortOption.value) {
    case 'createTimeDesc':
      params.orderByColumn = 'create_time';
      params.isAsc = 'desc';
      break;
    case 'createTimeAsc':
      params.orderByColumn = 'create_time';
      params.isAsc = 'asc';
      break;
    case 'updateTimeDesc':
      params.orderByColumn = 'update_time';
      params.isAsc = 'desc';
      break;
    case 'titleAsc':
      params.orderByColumn = 'article_title';
      params.isAsc = 'asc';
      break;
  }

  listHome(params).then(response => {
    articleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    updateFilterTags();
  });
}

// 更新过滤标签
function updateFilterTags() {
  activeTags.value = [];

  if (queryParams.value.articleTitle) {
    activeTags.value.push({
      type: 'articleTitle',
      value: queryParams.value.articleTitle,
      label: '标题',
      text: queryParams.value.articleTitle
    });
  }

  if (queryParams.value.status !== null && queryParams.value.status !== undefined) {
    const statusObj = bk_status.find(s => s.value == queryParams.value.status);
    if (statusObj) {
      activeTags.value.push({
        type: 'status',
        value: queryParams.value.status,
        label: '状态',
        text: statusObj.label
      });
    }
  }

  if (queryParams.value.categoryId) {
    const categoryObj = categoryOptions.value.find(c => c.value == queryParams.value.categoryId);
    if (categoryObj) {
      activeTags.value.push({
        type: 'categoryId',
        value: queryParams.value.categoryId,
        label: '分类',
        text: categoryObj.label
      });
    }
  }

  hasFilter.value = activeTags.value.length > 0;
}

// 移除过滤条件
function removeFilter(type, value) {
  queryParams.value[type] = null;
  handleQuery();
}

// 清除所有过滤条件
function clearAllFilters() {
  resetQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate() {
  const _id = ids.value[0];
  if (_id) {
    openNewPage(_id);
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row?.id || ids.value;
  proxy.$modal.confirm('是否确认删除文章信息编号为"' + _ids + '"的数据项？').then(function () {
    return delArticle(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('bk/article/export', {
    ...queryParams.value
  }, `article_${new Date().getTime()}.xlsx`)
}

// 监听排序选项变化
watch(sortOption, () => {
  getList();
});

// 监听视图模式变化
watch(viewMode, (newVal) => {
  // 如果切换到卡片或网格视图，可以调整每页显示数量
  if (newVal === 'card' || newVal === 'grid') {
    queryParams.value.pageSize = 12;
  } else {
    queryParams.value.pageSize = 10;
  }
  getList();
});

// 初始加载
getListcategory()
getList();
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.mb12 {
  margin-bottom: 12px;
}

.mb16 {
  margin-bottom: 16px;
}

.filter-tags {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

/* 卡片视图样式 */
.article-card-header {
  position: relative;
}

.card-image-container {
  width: 100%;
  height: 180px;
  overflow: hidden;
}

.card-status-tag {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 1;
}

.article-card-content {
  padding: 14px;
}

.article-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.article-excerpt {
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
  height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
}

.article-card-footer {
  border-top: 1px solid #EBEEF5;
  padding: 10px;
  display: flex;
  justify-content: flex-end;
}

/* 表格视图样式 */
.title-cell {
  text-align: left;
}

.article-title-preview {
  font-weight: bold;
  margin-bottom: 5px;
}

.article-excerpt-preview {
  color: #909399;
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 300px;
}

/* 网格视图样式 */
.grid-item {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
  height: 100%;
}

.grid-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.grid-item-image {
  position: relative;
  height: 120px;
  overflow: hidden;
}

.grid-status {
  position: absolute;
  top: 8px;
  right: 8px;
}

.grid-content {
  padding: 12px;
}

.grid-title {
  margin: 0 0 8px;
  font-size: 16px;
}

.grid-category {
  color: #409EFF;
  margin: 5px 0;
  font-size: 13px;
}

.grid-date {
  color: #909399;
  font-size: 12px;
  margin: 5px 0;
}

.grid-actions {
  padding: 0 12px 12px;
  display: flex;
  justify-content: center;
}

.text-overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>